package com.heartech.prediciton_wx.service.qrcode;

import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class QrCodeStateManager {
    private final ConcurrentHashMap<String, ReentrantLock> qrCodeLocks = new ConcurrentHashMap<>();

    public boolean tryProcessQrCode(String qrCode) {
        // 如果当前没有其他线程在处理这个二维码，获取锁并返回true
        ReentrantLock lock = qrCodeLocks.computeIfAbsent(qrCode, k -> new ReentrantLock());
        if (lock.tryLock()) {
            return true;
        } else {
            // 如果已经有其他线程在处理这个二维码，返回false
            return false;
        }
    }

    public void releaseQrCode(String qrCode) {
        // 释放二维码，以便其他用户可以处理
        ReentrantLock lock = qrCodeLocks.get(qrCode);
        if (lock != null) {
            lock.unlock();
        }
    }
}
